<template>
  <section >
    <!--操作区域-->
    <el-row >
      <el-col :span="24">
        <strong>设置说明：</strong>目前仅支持保留您前次所做设置，
        <br>
        <strong>宽高及页数换算：</strong>单位:毫米，支持类型：ISO216(A/B/C系列 0-10),JIS(B系列 0-9)
        <br>
        <span  style="color:#e6a23c">
          打印预览窗口同时只允许出现一个，若出现打印异常，您可以自行调整宽高
        </span>
        <br>
        <span  style="color:#e6a23c">
          三联纸：宽243，高135，纵向打印
        </span>
      </el-col>
    </el-row>
    <el-row style="    padding: 11px 0px;">
      <el-col :span="12">
        <el-button style="width: 90px;">打印机:</el-button>
        <el-select ref="printer" v-model="printerSelId" filterable  placeholder="请选择" @change="selectChange" style="    width: 200px;">
          <el-option
            v-for="item in printers"
            :key="item.name"
            :label="item.name"
            :value="item.name">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="12">
        <el-button style="width: 90px;">打印方向:</el-button>
        <el-select ref="printerOrient" v-model="printerSelOrient" filterable  placeholder="请选择" @change="selectOrientChange" style="    width: 220px;margin-right: 11px">
          <el-option label="纵向打印，固定纸张" value="1"  key="1"></el-option>
          <el-option label="横向打印，固定纸张" value="2" key="2"></el-option>
          <el-option label="纵向打印，高度自适应" value="3" key="3"></el-option>
        </el-select>
      </el-col>
    </el-row>
    <el-row  style="    padding: 11px 0px;">
      <el-col :span="12">
        <el-button style="width: 90px;">纸张:</el-button>
        <el-select ref="printerPage" v-model="printerSelPage" filterable  placeholder="请选择" @change="selectPageChange" style="    width: 200px;">
          <el-option
            v-for="item in printer.pagelist"
            :key="item.name"
            :label="item.name"
            :value="item.name">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="12">
        <el-button style="width: 50px;">宽度:</el-button>
        <el-input ref="printerPageWidth" @change="printerPageWidthChange"  placeholder="0-9999" v-model="printerPageWidth" type="number" maxlength="4" style="width: 100px;margin-right: 11px"></el-input>

        <el-button style="width: 50px;">高度:</el-button>
        <el-input @change="printerPageHeightChange"  placeholder="0-9999" v-model="printerPageHeight" type="number" maxlength="4" style="width: 100px"></el-input>
      </el-col>
    </el-row>
    <el-row  style="    padding: 11px 0px;">
      <el-col :span="24">
        <el-button style="width: 90px;">每页数量:</el-button>
        <el-input @change="printerPageChange"  placeholder="0-100" v-model="printerPageSize" type="number" maxlength="3" style="width: 100px;margin-right: 11px"></el-input>
        <el-checkbox @change="titleEveryPageChange"  v-model="titleEveryPage" style="width: 120px">每页显示标题</el-checkbox>
        <el-checkbox @change="headEveryPageChange"  v-model="headEveryPage" style="width: 120px">每页显示表头</el-checkbox>
        <el-checkbox @change="footEveryPageChange"  v-model="footEveryPage" style="width: 120px">每页显示表尾</el-checkbox>
      </el-col>
    </el-row>
    <el-row  style="    padding: 11px 0px;">
      <el-col :span="24">
        <el-checkbox @change="lineBreakChange"  v-model="lineBreak" style="width: 120px">自动换行</el-checkbox>
      </el-col>
    </el-row>
    <el-row  style="    padding: 11px 0px;text-align: center;">
      <el-col :span="22">
        <el-button ref="btnPrint" v-show="isPrint"  @click="print(false)" type="primary"  >打印</el-button>
        <el-button ref="btnView"  v-show="isPrint"   @click="print(true)" type="primary"  >预览</el-button>
        <el-button  @click="utils.downloadStatic('exe', 'CLodop_Setup_for_Win32NT')"   >下载客户端</el-button>
        <el-button  @click="close" >关闭</el-button>
      </el-col>
    </el-row>

    <!--打印区域-->
    <div ref="printBox" id="printBox" class="print-box" >
      <div   v-for="(param,indexArr) in paramArr" :key="indexArr" >
        <div class="dataTableBox"   v-for="(pageNum,index0) in Math.ceil((param.tableData ? param.tableData.length: 0)/printerPageSize)" :key="index0" :style="{paddingTop:'9px',width: (printerPageWidth-9)*mmRatePx-20+'px'}">
          <!--分页-->
          <div style="text-align: right; padding-right: 11px;height: 0px;width: 100%;   margin-left: -25px;zoom: 90%">
            <span style="">{{pageNum}}/{{Math.ceil((param.tableData ? param.tableData.length: 0)/printerPageSize)}}</span>
          </div>
          <!--标题-->
          <div v-if="(titleEveryPage || pageNum == 1 )  && param.title" class="title" style="text-align: center;    font-size: 18px;font-weight: bold; padding-bottom: 5px;width: 90%;">
            {{param.title}}
          </div>
          <!--子标题-->
          <div v-if="(titleEveryPage || pageNum == 1 )  && param.subtitle" class="subtitle" style="text-align: center;    font-size: 14px;height:30px">
            {{param.subtitle}}
          </div>

          <!--表头-->
          <div class="head"  v-if="(headEveryPage || pageNum == 1) &&  (param.head || param.sumData)" style="padding-bottom: 8px;width: 90%;">
            <div :key="ob.name" v-for="ob in param.head" :style="getHeadFootColStyle(ob)">
              <div :style="getHeadFootColLabelStyle(ob)" >{{ob.text}}:</div>
              <div :style="getHeadFootColValueStyle(ob)" >{{getHeadFootValue(ob, param)}}</div>
            </div>
            <div :key="ob.field" v-for="ob in param.sumData" v-if="!param.config.flagTopSum" :style="getHeadFootColStyle(ob, true)">
              <div :style="getHeadFootColLabelStyle(ob, true)" >{{ob.label}}:</div>
              <div :style="getHeadFootColValueStyle(ob)" >{{ob.sum}}</div>
            </div>
          </div>

          <!--非动态列数据区域-->
          <table class="dataTable" style="border-collapse: collapse;width: 100%;    table-layout: fixed;margin-left: -25px;zoom: 90%"  v-if="!param.config.flagDynamicColumn && !param.config.flagFixedColumn">
            <thead class="dataTableHead">
            <tr>
              <th style="width: 30px;">
              </th>
              <th  style="width: 30px;text-align: center;border:1px solid black; font-size: 14px; font-weight: bold" v-if="!param.config.noPrintSeq">
                <span>序号</span>
              </th>
              <th :style="getDataTableHeadThStyle(column,param.columnAllWidth)"  v-if="!column.flagNorint && column.field !='seq'"  v-for="column in param.columns" :key="column.field" >
                <span>{{utilFieldMap.show(column.field, column.label)}}</span>
              </th>
            </tr>
            </thead>
            <tbody class="dataTableBody">
            <tr v-for="(row,index) in param.tableData" :key="index" v-if="index>=(pageNum-1)*printerPageSize &&  index < pageNum*printerPageSize  " >
              <td >
              </td>
              <td v-if="row.index != '合计' && !param.config.noPrintSeq " style="border:1px solid black;font-size: 14px;">
                <span >{{index+1}}</span>
              </td>
              <td v-else-if="!param.config.noPrintSeq" style="text-align: right;font-weight: bold;border:1px solid black;font-size: 14px;">
                <span >{{row.index}}</span>
              </td>
              <td  v-for="column in param.columns"  v-if="!column.flagNorint && column.field !='seq'"   :key="column.field" :style="getDataTableBodyTdStyle(row)">
                <span  v-if="column.datePattern ">{{ dates.formatToAnotherPattern(row[column.name], column.datePattern)}}</span>
                <span  v-else>{{getCellValue(row, column)}}</span>
              </td>
            </tr>

            <!--合计-->
            <tr class="sum"  v-if=" Math.ceil(param.tableData.length/printerPageSize) > 0 && pageNum-1 != Math.ceil(param.tableData.length/printerPageSize)">
              <td style="text-align: right;font-size: 14px; font-weight: bold ">
                <span style="    margin-right: -28px;">小计</span>
              </td>
              <td v-if="!param.config.noPrintSeq " style="border:1px solid black;font-size: 11px;">
              </td>
              <th  v-for="column in param.columns" :key="column.field" v-if="!column.flagNorint  && column.field !='seq' " :style="getColumnSumStyle(column)" >
                <span > {{getColumnSUm(param.tableData,column.field,pageNum)}}</span>
              </th>
            </tr>
            </tbody>
          </table>

          <!--动态列数据区域-->
          <table class="dataTable" style="border-collapse: collapse;width: 100%;    table-layout: fixed;margin-left: -25px;zoom: 90%"  v-if="param.config.flagDynamicColumn || param.config.flagFixedColumn">
            <tr>
              <th :rowspan="getColumnChildren(param.columns).length > 0 ? 2 : 1"  style="width: 30px;">
              </th>
              <th :rowspan="getColumnChildren(param.columns).length > 0 ? 2 : 1"  style="width: 30px;text-align: center;border:1px solid black; font-size: 14px; font-weight: bold" v-if="!param.config.noPrintSeq">
                <span>序号</span>
              </th>
              <th :style="getDataTableHeadThStyle(column,param.columnAllWidth, column.children)"  :rowspan="column.children && column.children.length > 0 ? 1 : 2" :colspan="column.children && column.children.length > 0 ? column.children.length : 1 "  v-if="!column.flagNorint && column.field !='seq' && column.children"  v-for="column in param.columns" :key="column.field" >
                <span>{{utilFieldMap.show(column.field, column.label)}}</span>
              </th>
            </tr>

            <tr v-if="getColumnChildren(param.columns).length > 0">
              <th :style="getDataTableHeadThStyle(column,param.columnAllWidth)"   rowspan="1"      v-for="column in getColumnChildren(param.columns)" :key="column.field" >
                <span>{{utilFieldMap.show(column.field, column.label)}}</span>
              </th>
            </tr>


            <tbody class="dataTableBody">
            <tr v-for="(row,index) in param.tableData" :key="index" v-if="index>=(pageNum-1)*printerPageSize &&  index < pageNum*printerPageSize  " >
              <td >
              </td>
              <td v-if="row.index != '合计' && !param.config.noPrintSeq " style="border:1px solid black;font-size: 14px;">
                <span >{{index+1}}</span>
              </td>
              <td v-else-if="!param.config.noPrintSeq" style="text-align: right;font-weight: bold;border:1px solid black;font-size: 14px;">
                <span >{{row.index}}</span>
              </td>
              <td  v-for="column in getColumnAll(param,param.columns)"  v-if="!column.flagNorint && column.field !='seq'"   :key="column.field" :style="getDataTableBodyTdStyle(row)">
                <span  v-if="column.datePattern ">{{ dates.formatToAnotherPattern(row[column.name], column.datePattern)}}</span>
                <span  v-else>{{getCellValue(row, column)}}</span>
              </td>
            </tr>

            <!--合计-->
            <tr class="sum"  v-if="!param.config.flagBottomSum && Math.ceil(param.tableData.length/printerPageSize) > 0 && pageNum-1 != Math.ceil(param.tableData.length/printerPageSize)">
              <td style="text-align: right;font-size: 14px; font-weight: bold ">
                <span style="    margin-right: -28px;">小计</span>
              </td>
              <td v-if="!param.config.noPrintSeq " style="border:1px solid black;font-size: 11px;">
              </td>
              <th  v-for="column in getColumnAll(param,param.columns)" :key="column.field" v-if="!column.flagNorint  && column.field !='seq' "   :style="getColumnSumStyle(column)" >
                <span > {{getColumnSUm(param.tableData,column.field,pageNum, column)}}</span>
              </th>
            </tr>
            </tbody>
          </table>

          <!--表尾部-->
          <div class="foot" v-if="(footEveryPage || pageNum == Math.ceil(param.tableData.length/printerPageSize))  && param.foot" style="padding-top: 8px; width: 90%;">
            <div :key="ob.name" v-for="ob in param.foot"   :style="getHeadFootColStyle(ob)">
              <div :style="getHeadFootColLabelStyle(ob)" >{{ob.text}}:</div>
              <div :style="getHeadFootColValueStyle(ob)"  >{{getHeadFootValue(ob, param)}}</div>
            </div>
          </div>

        </div>
      </div>
    </div>
  </section>
</template>

<script>
/*eslint-disable*/
import {getLodop} from '@/util/lodop/LodopFuncs.js'
import LodopModel from '@/util/lodop/LodopModel.js'
import FortenCode from '@/components/common/FortenCode.vue'

export default {
  name: 'printForm',
  props: ['paramArr'],
  components: {FortenCode},
  data() {
    return {
      //表格数据
      tableData: [],
      //表格列
      columns: [],
      paramArrPrint: [],
      //Lodop实例,单例
      userLodopModel: null,

      //所选打印机
      printerSelId: null,
      printer: {},
      printers: [],

      //打印服务器
      printerServers: [],
      printerServer: {},
      printerServerSelId: null,
      printType: 'form',

      //界面所设置的属性
      printerSelPage: 'A4',
      printerSelOrient: '1',
      printerPageSize: 20,
      printerPageWidth: 210,
      printerPageHeight: 297,
      headFootColLabelMax: null,
      sumPageNum: 0,
      titleEveryPage: true,
      headEveryPage: true,
      footEveryPage: true,
      lineBreak: false,
      paperSizeMapNames: '',
      //毫米跟像素的换算比率,基本上 1毫米 约等于 3.78像素，此处取整
      mmRatePx: 3.78,

      //数据是否成功加载过一次
      dataLoadOnceSuccess: false,
      isPrint: true,
      printAuto: false
    }
  },

  watch:{
    //参数变化后，进行初始化
    paramArr:{
      handler(newValue, oldValue) {
        if (!this.dataLoadOnceSuccess && this.paramArr && this.paramArr.length >0){
          this.initPrintOnce()
        }
      },
      deep: true,
      immediate: true
    }
  },

  methods: {
    //关闭窗口
    close(){
      this.$emit("printFormClose")
    },

    //初始化打印列表
    async initPrintOnce(){
      global.utilPrint.isNeedCLodopfuncs()
      this.dataLoadOnceSuccess = true
      setTimeout(() => {
        if(this.initPrint() ) {
          // this.getHeadFootColLabelMax()

          //自动打印
          if (this.printAuto) {
            this.utilMessage.success('自动打印中（若无反应，请检查打印机是否可用），请稍候')
            this.print(false)
          }
        }
      }, 500)
    },

    //初始化打印设置
    initPrint(){
      var param={
        checkUsable:true
      }
      if(!this.userLodopModel || !this.userLodopModel.lodop){
        this.userLodopModel = new window.LodopModel(param)
      }
      if(!this.userLodopModel.lodop ){
        this.$confirm('未发现可用的打印服务,是否立即下载打印程序？<br><small>确认，下载安装后重新进入打印界面即可。</small><br><small>取消，将关闭打印窗口</small><br><small style="color:#e6a23c">安装时若安全软件提示修改URL关联，请允许</small>', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          type: 'warning'
        }).then(() => {
          this.utils.downloadStatic('exe', 'CLodop_Setup_for_Win32NT')
          this.close()
        }).catch(() => {
          this.close()
        })
        return false
      }
      if(this.userLodopModel.lodop){
        //打印机列表
        this.printers = this.userLodopModel.getPrinters() || []

        //上次所选打印机
        let printer_form_name = this.utils.loadUserState(this,'printerFormName')
        let printerOb = this.printers.find(item => item.name == printer_form_name)
        printer_form_name = printerOb ? printerOb.name : null
        if(!printer_form_name ) printer_form_name= this.printers[0].name
        this.printerSelId = printer_form_name
        this.printer = this.printers.find(item => item.name == printer_form_name)

        //上次所选纸张
        this.printerSelPage = this.utils.loadUserState(this,'printerFormPage')

        //上次所设置宽度
        this.printerPageWidth = this.utils.loadUserState(this,'printerFormPageWidth') || this.printerPageWidth

        //上次所设置高度
        this.printerPageHeight = this.utils.loadUserState(this,'printerFormPageHeight') || this.printerPageHeight

        //上次所选方向
        this.printerSelOrient = this.utils.loadUserState(this,'printerFormOrient')

        //上次所选每页数量
        this.printerPageSize = this.utils.loadUserState(this,'printerFormPageSize') || this.printerPageSize

        //上次所设置每页显示标题
        this.titleEveryPage = this.utils.loadUserState(this,'printerFormTitleEveryPage',null, true,this.titleEveryPage)

        //上次所设置每页显示表头
        this.headEveryPage = this.utils.loadUserState(this,'printerFormHeadEveryPage',null, true,this.headEveryPage)
        //上次所设置每页显示表尾
        this.footEveryPage = this.utils.loadUserState(this,'printerFormFootEveryPage',null, true,this.footEveryPage)

        //上次所设置自动换行
        this.lineBreak = this.utils.loadUserState(this,'printerFormLineBreak',null, true,this.lineBreak)

        //自动打印
        this.printAuto = this.utils.loadUserState(this,'printerFormPrintAuto',null, true,this.printerFormPrintAuto)

        return true
      }else{
        return false
      }
    },

    //打印机选择后
    selectChange(name) {
      this.printer = this.printers.find(item => item.name == name)
      this.printerSelPage = null
      this.$refs.printerPage.focus()
      this.utilPrint.updateWorkSet(name)
      this.utils.updateUserState('printerFormName', name, this)
    },
    //打服务器选择后
    printerServerChange(id) {
      this.printerServer = this.printerServers.find(item => item.id == id)
      this.utils.updateUserState('printer_form_serverid', id, this)
    },

    //纸张选择后
    selectPageChange(name) {
      this.utils.updateUserState('printerFormPage', name, this)
      let pageSize = global.utilPrint.getPaperSize(name)
      if(!pageSize) {
        this.utilMessage.warning('您所选择的纸张【'+name+'】未能找到有效的尺寸，请自行设置')
        this.$refs.printerPageWidth.focus()
        return
      }
      this.printerPageWidth = pageSize.width
      this.printerPageHeight = pageSize.height
      this.printerPageWidthChange(this.printerPageWidth)
      this.printerPageHeightChange(this.printerPageHeight)
    },

    //宽度选择后
    printerPageWidthChange(name) {
      this.utils.updateUserState('printerFormPageWidth', name, this)
    },

    //高度选择后
    printerPageHeightChange(name) {
      /**根据纸张高度计算每页数量
       * 基本上 1毫米 约等于 3.78像素
       * 每页数量（向下取整）=（纸张高度-非数据表格数据）/单行高度
       */
      let maxH=this.printerPageHeight*this.mmRatePx
      if($('.title:first').length >0) maxH -= $('.title:first').height()
      if($('.head:first').length >0) maxH -= $('.head:first').height()
      if($('.dataTableHead:first').length >0) maxH -= $('.dataTableHead:first').height()
      if($('.dataTableHead:first').length >0) maxH -= $('.dataTableHead:first').height()
      if($('.sum:first').length >0) maxH -= $('.sum:first').height()
      if($('.foot:first').length >0) maxH -= $('.foot:first').height()
      this.printerPageSize = parseInt(maxH/50)

      this.utils.updateUserState('printerFormPageHeight', name, this)
    },

    //方向选择后
    selectOrientChange(name) {
      if (name == '2') { //横向打印
        //宽度小于高度，则进行逆转
        if (this.printerPageWidth < this.printerPageHeight) {
          let printerPageWidthTmp = this.printerPageWidth
          this.printerPageWidth = this.printerPageHeight
          this.printerPageHeight = printerPageWidthTmp
          this.printerPageWidthChange(this.printerPageWidth)
          this.printerPageHeightChange(this.printerPageHeight)
        }
      } else{//纵向打印
        //宽度大于高度，则进行逆转
        if (this.printerPageWidth > this.printerPageHeight) {
          let printerPageWidthTmp = this.printerPageWidth
          this.printerPageWidth = this.printerPageHeight
          this.printerPageHeight = printerPageWidthTmp
          this.printerPageWidthChange(this.printerPageWidth)
          this.printerPageHeightChange(this.printerPageHeight)
        }
      }
      this.utils.updateUserState('printerFormOrient', name, this)
    },

    //每页数量选择后
    printerPageChange(name) {
      this.utils.updateUserState('printerFormPageSize', name, this)
    },

    //每页显示标题选择后
    titleEveryPageChange(name) {
      this.utils.updateUserState('printerFormTitleEveryPage', name, this)
    },

    //每页显示表头选择后
    headEveryPageChange(name) {
      this.utils.updateUserState('printerFormHeadEveryPage', name, this)
    },

    //自动换行
    lineBreakChange(name) {
      this.utils.updateUserState('printerFormLineBreak', name, this)
    },

    //每页显示表尾选择后
    footEveryPageChange(name) {
      this.utils.updateUserState('printerFormFootEveryPage', name, this)
    },

    //获取表头和表尾标题宽度，取最多标题的宽度
    getHeadFootColLabelMax(param){
      if(this.headFootColLabelMax) return this.headFootColLabelMax
      let strMax=''
      if(param.head && param.head.length>0) {
        param.head.forEach(ob =>  {
          if(ob.text.length > strMax.length) strMax = ob.text
        })
      }
      if(param.foot && param.foot.length>0) {
        param.foot.forEach(ob =>  {
          if(ob.text.length > strMax.length) strMax = ob.text
        })
      }
      this.headFootColLabelMax = strMax.length*16+'px'
      return this.headFootColLabelMax
    },

    //表头表尾列样式
    getHeadFootColStyle(ob, isSum){
      let style = {float: 'left', padding: '4px 0px'}
      if ( (isSum && isSum == true)) {
        style.paddingRight = '11px'
        return style
      }
      if(!ob.col && (isSum && isSum == true)) ob.col = 4
      if(!ob.col) ob.col = 8
      //宽度: 百分比
      let width = ob.col/24*100+'%'
      style.width = width
      style.maxWidth = width
      style.overflowX = 'hidden'
      return style
    },

    //表头列标题样式
    getHeadFootColLabelStyle(ob, isSum){
      let style = {float: 'left', fontWeight: 'bold',fontSize: '12px', width: this.getHeadFootColLabelMax(this.paramArr[0]) }
      if ( (isSum && isSum == true)) {
        style.width = 'auto'
        return style
      }
      return style
    },


    //单元格数据
    getCellValue(row, column){
      let value = row[column.field]
      if (column.queryType && column.queryType =='select') {
        //value, type, defaultValue, showColor
        value = this.utils.getDictLabel(value, column.dict,value, false)
      }
      return value
    },

    //表格标题列样式
    getDataTableHeadThStyle(column, columnAllWidth, children){
      let style = {textAlign: 'center', border: '1px solid black', padding: '0px 0px',fontSize: '14px',fontWeight: 'bold'}
      let title = column.title
      let width = 'auto'
      if (children && children.length > 0){
        let width = 0
        children.forEach(column => {
          if (column.width != 'auto') {
            width += parseInt(column.width)
          }
        })
        width = width/(columnAllWidth)*100
        style.width = width +'%'

      } else {
        //宽度= 当前列宽度/所有需要打印的列的总宽度  * 纸张宽度
        let width = 'auto'
        if (column.width != 'auto') {
          width = parseInt(column.width)/(columnAllWidth)*100
          style.width = width +'%'
          // style.maxWidth = width +'%'
        }
      }

      return style
    },

    //表格数据列样式
    getDataTableBodyTdStyle(column){
      let style = { border: '1px solid black',fontSize: '14px'}
      // let width = (ob.col/24*100)*this.printerPageWidth*this.mmRatePx
      if (!this.lineBreak) {
        style.overflow = 'hidden'
        style.whiteSpace = 'nowrap'
        style.textOverflow = 'unset'
      } else {
        style.wordBreak = 'break-all'
      }
      return style
    },

    //表头表尾数据列样式
    getHeadFootColValueStyle(ob){
      let style = {float: 'left',fontSize: '12px'}
      return style
    },

    //表头表尾数据
    getHeadFootValue(ob, param){
      if(!ob.value) ob.value = param.form[ob.name]
      if(ob.dateFmt &&  ob.value)  ob.value = dates.formatToAnotherPattern(ob.value, ob.dateFmt)
      return ob.value
    },

    //获取列合计
    getColumnSUm(tableData, name,pageNum, column){
      //FlagFootSum
      if(name.indexOf('qty') == -1 && name.indexOf('amount') == -1 && name.indexOf('sum') == -1 && name.indexOf('00') == -1 ){
        if (!column || !column.flagFootSum) {
          return ''
        }
      }
      let sum = 0
      tableData.forEach( (ob,index) => {
        if ( index>=(pageNum-1)*this.printerPageSize &&  index < pageNum*this.printerPageSize ) {
          sum+=ob[name]
        }
      })
      return utilNum.toFixed(sum)
    },


    //合计列列样式
    getColumnSumStyle(column){
      let style = { border: '1px solid black',fontSize: '14px',fontWeight: 'bold',textAlign: 'right'}
      if (!this.lineBreak) {
        style.overflow = 'hidden'
        style.whiteSpace = 'nowrap'
        style.textOverflow = 'unset'
      } else {
        style.wordBreak = 'break-all'
      }
      return style
    },

    //打印窗口打开后，数据只查询一次
    async initData() {

      let that = this
      let param
      for(var index=0; index< this.paramArr.length ; index++){
        param = this.paramArr[index]
        let queryWrapper = param.queryWrapper
        const params = {
        }
        if (queryWrapper && queryWrapper.queryConditions) params.queryString = JSON.stringify(queryWrapper.queryConditions)
        let url = `/report/config/fetchDataForPrint?reportKey=${param.config.code}`
        await this.$ajax.get(url, { params }).then((response) => {
          if (response.code == 0) {
            response.data = this.getShowData(response.data)
            that.paramArrPrint.push(response.data)
            that.$set(that.paramArr[index],'config',response.data.config)
            that.$set(that.paramArr[index],'tableData',response.data.data)
            that.$set(that.paramArr[index],'columns',response.data.gridFields)
            that.$set(that.paramArr[index],'sumData',response.data.sumData)
            that.$set(that.paramArr[index],'columnAllWidth',this.getColumnAllWidth(response.data.gridFields))
          }
        })
      }
      this.dataLoadOnceSuccess = true
    },

    getColumnAllWidth(gridFields) {
      let columnAllWidth = 0
      //动态列字段
      gridFields.forEach((column,index2) => {
        if (!column.flagShow || column.flagNorint == true || column.width == 'auto' || isNaN(parseInt(column.width))) {
          return true;
        }

        columnAllWidth+= parseInt(column.width)
      })
      return columnAllWidth
    },
    getShowData(respData) {
      if (!respData.config.flagDynamicColumn && !respData.config.flagFixedColumn) {
        return respData;
      }      //转换动态列数据
      let dataNew = []

      let pkName = []
      let dataUnique = respData.data.filter((row) => !pkName.includes(row.pk) && pkName.push(row.pk))

      //如果动态列没有一条数据，则不显示
      let gridFieldsNew = respData.gridFields.filter(gridField => {
        if (gridField.flagGroup == true || this.strings.isNotBlank(gridField.parentField))  return false
        if (gridField.flagDynamicColumn || gridField.field == 'seq') {
          gridField.sortable = false
        } else {
          gridField.sortable = true
        }

        let gridFieldsNew2 = respData.gridFields.filter(gridField2 => gridField2.groupField == gridField.field  || gridField2.parentField == gridField.field)
        gridField.children = gridFieldsNew2
        return gridField.flagShow
      })


      //拼接动态列数据
      dataUnique.forEach((row,index) => {
        //动态列字段
        gridFieldsNew.forEach((column,index2) => {
          if (!column.flagDynamicColumn || column.flagDynamicColumn != true) return true;
          if (index == 0 && index2 == 0) {
          }
          //列数据
          let dataHit = respData.data.filter((rowData) => {
            return rowData.pk == row.pk && rowData.field == column.field
          } )

          if (dataHit && dataHit.length > 0) {
            let amountSUm = 0
            dataHit.forEach((ob) => amountSUm+=ob.amount )
            dataUnique[index][column.field] = amountSUm
          } else {
            // dataUnique[index][column.field] = 0
          }
        })
      })

      respData.data = dataUnique
      respData.gridFields = gridFieldsNew

      return respData;

    },

    //打印或者预览
    async print(ispRreview) {
      if (!this.printerSelId) {
        this.utilMessage.warning('请选择打印机')
        this.$refs.printer.focus()
        return
      }
      if (!this.printerSelPage) {
        this.utilMessage.warning('请选择纸张')
        this.$refs.printerPage.focus()
        return
      }
      if (!this.printerSelOrient) {
        this.utilMessage.warning('请选择方向')
        this.$refs.printerOrient.focus()
        return
      }

      this.utilVue.loadShow(true)
      await  this.initData()
      let that = this
      setTimeout( () => {
        //分页
        $('.pagebreak').remove()
        let dataTableNum = $('.dataTableBox').length
        if(dataTableNum >1){
          $('.dataTableBox').append('<div class="pagebreak" style="page-break-after:always">&nbsp;&nbsp;&nbsp;</div>')
          $('.pagebreak:last').remove()
        }

        //设置打印机属性
        that.userLodopModel.printerName = that.printerSelId
        that.userLodopModel.printerOrient = that.printerSelOrient
        that.userLodopModel.printerPageWidth = that.printerPageWidth
        that.userLodopModel.printerPage = that.printerSelPage
        that.userLodopModel.printerPageHeight = that.printerPageHeight

        let printBox = $(that.$refs.printBox)
        that.userLodopModel.addPrintHtml(printBox.prop("outerHTML"))
        let retMsg = null

        //设置打印机
        var ret3=that.userLodopModel.lodop.SET_PRINTER_INDEXA(that.printerSelId);
        if(!ret3) {
          global.utilMessage.alertFail(`目标打印机不可使用`, '系统提示', {
            confirmButtonText: '确定',
            type: 'warning',
            callback: action => {
            }
          })
          retrun
        }

        //虚拟打印机，指定纸张宽度
        if (that.printerSelId.toLowerCase().indexOf('pdf') != -1 || that.printerSelId.toLowerCase().indexOf('onenote') != -1
          || that.printerSelId.toLowerCase().indexOf('xps') != -1 || that.printerSelId.toLowerCase().indexOf('fax') != -1) {
          that.userLodopModel.lodop.SET_PRINT_PAGESIZE(that.printerSelOrient, that.printerPageWidth, 0,that.printerPageHeight);
        } else { //真实打印机，指定纸张名称
          that.userLodopModel.lodop.SET_PRINT_PAGESIZE(that.printerSelOrient,0,that.printerPageHeight,that.printerSelPage);
        }

        if (ispRreview) {
          that.utilVue.loadHide()
          //预览窗口已打开
          if(that.userLodopModel.lodop.OBO_Mode && that.userLodopModel.lodop.blOneByone) {
            that.$alert(`预览窗口已打开，请到任务栏找到打印预览图标进行关闭，然后重新尝试预览操作`, '系统提示', {
              confirmButtonText: '确定',
              type: 'warning',
              callback: action => {
              }
            })
            retrun
          }
          that.userLodopModel.lodop.SET_PREVIEW_WINDOW(1,2,1,1000,800,"打印预览");

          //预览窗口禁止最小化，并始终最前
          that.userLodopModel.lodop.SET_SHOW_MODE("PREVIEW_NO_MINIMIZE",true)
          that.userLodopModel.lodop.PREVIEW();
        } else {

          that.userLodopModel.lodop.SET_PRINT_MODE("CATCH_PRINT_STATUS",true)

          let printValue = null

          that.userLodopModel.lodop.On_Return=function(TaskID,Value){
            printValue = Value

            var strResult
            try{
              strResult=that.userLodopModel.lodop.GET_VALUE('PRINT_STATUS_ID',printValue)
            }catch (e) {
              console.error('GET_VALUE',e)
            }
            setTimeout(() => {
              that.utilMessage.success('打印任务已提交')
              that.utilVue.loadHide()
              if ( that.printAuto) that.close()
            }, 1000)

          };
          let ret = that.userLodopModel.lodop.PRINT();

          this.paramArr.forEach((item,index) => {
            if (item.tableName && item.pkName && item.pkValue){
              let ids = item.pkValue;
              let tableName = item.tableName;
              let pkName = item.pkName;
              ids.forEach(item=>{
                global.utilPrint.updateFormPrintTime(tableName,pkName,item)
              })
            }
          })

        }
      },1000)
    },

    //查询打印服务器
    async getPrinterServers(){
      //printType
      let wrapper = this.$newWrapper()

      if (this.printType == 'form') {
        wrapper.eq('typeKey', 'form')
      } else {
        wrapper.eq('typeKey', 'rfid').or('typeKey', 'label')
      }

      const params = {
        queryString: this.utils.json2str(wrapper.queryConditions)
      }
      await this.$ajax.get('/sys/printer/list',{params}).then(resp => {
        if (resp.code == 0) {
          this.printerServers = resp.data
        }
      })
    },

    getColumnChildren(columns) {
      if (!columns || columns.length < 1)  return []
      let children = []
      columns.forEach(column => {
        if (column.children) children = children.concat(column.children)
      })
      return children
    },

    getColumnAll(param, columns) {
      let children = []
      param.columns.forEach(column => {
        if (column.children && column.children.length > 0) {
          children = children.concat(column.children)
        } else {
          children.push(column)
        }
      })
      return children
    }
  }
}
</script>

<style lang="scss" scoped>
  .container{
    padding: 5px;
  }
  .print-box {
    border: 3px dotted #1890FF;
    overflow-x: auto;
   /* position: absolute;
    top: 999999999px;*/
  }
</style>
